#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileInfo>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    startedSearch(false)
{
    ui->setupUi(this);
    connect(ui->mapWidget, SIGNAL(displayPath(QString)), this, SLOT(pathFound(QString)));
    connect(ui->mapWidget, SIGNAL(sendMessage(QString)), this, SLOT(addStatus(QString)));
    connect(this, SIGNAL(sendPause(void)), ui->mapWidget, SLOT(pauseThread(void)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_fileSelectButton_clicked()
{
    inputFilesDialog = new FileSelector(this);
    inputFilesDialog->setWindowTitle("File Selection");
    if (inputFilesDialog->exec() == QDialog::Accepted)
    {
        QString locsFilePath = inputFilesDialog->getLocationsFilename();
        QString connsFilePath = inputFilesDialog->getConnectionsFilename();

        if (locsFilePath.size() == 0 || connsFilePath.size() == 0)
            return;

        QFileInfo locsInfo(locsFilePath);
        QFileInfo connsInfo(connsFilePath);

        ui->locationsFileLabel->setText(locsInfo.fileName());
        ui->connectionsFileLabel->setText(connsInfo.fileName());

        ui->mapWidget->buildMap(locsFilePath, connsFilePath);
        QStringList nodeNameList = ui->mapWidget->getNodeNames();
        qSort(nodeNameList);

        ui->startPointBox->clear();
        ui->destinationPointBox->clear();
        ui->excludedPointBox->clear();

        ui->startPointBox->addItems(nodeNameList);
        ui->destinationPointBox->addItems(nodeNameList);
        ui->excludedPointBox->addItems(nodeNameList);

        ui->destinationPointBox->setCurrentIndex(1);
        ui->excludedPointBox->insertItem(0, "");
        ui->excludedPointBox->setCurrentIndex(0);

        ui->mapWidget->drawPoints();
        ui->mapWidget->drawConnections();

        ui->mapWidget->repaint();
    }
    delete inputFilesDialog;
}

void MainWindow::on_startButton_clicked()
{
    if(!startedSearch)
    {
        startedSearch = true;
        QString startName = ui->startPointBox->currentText();
        QString destinationName = ui->destinationPointBox->currentText();
        QString excludedName = ui->excludedPointBox->currentText();

        if (ui->mapWidget->setPoints(startName, destinationName, excludedName))
        {
            ui->mapWidget->clearMap();
            ui->outPath->clear();
            ui->statusText->clear();
            ui->mapWidget->runAStar();
        }
        else
        {
            if(startName == excludedName)
                ui->statusText->append("Cannot exclude start node.");
            else
                ui->statusText->append("Cannot exclude destination node.");
        }
    }

}

void MainWindow::on_pauseButton_clicked()
{
    emit sendPause();
}

void MainWindow::pathFound(QString path)
{
    ui->outPath->setText(path);
    startedSearch = false;
}

void MainWindow::addStatus(QString msg)
{
    ui->statusText->append(msg);
}
